package com.tron.dobest.netty.socket;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.ContinuationWebSocketFrame;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;

/**
 * 描述：
 *
 * @author TRON
 * @since 2020-06-18
 */
@Sharable
public class ContinuationWebSocketFrameHandler extends SimpleChannelInboundHandler<ContinuationWebSocketFrame> {

    private ChannelGroup group;

    private ByteBuf buf = null;

    public ContinuationWebSocketFrameHandler(ChannelGroup group) {
        this.group = group;
    }


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ContinuationWebSocketFrame continuationWebSocketFrame) throws Exception {
        boolean finalFragment = continuationWebSocketFrame.isFinalFragment();
        System.out.println("处理分片二进制数据" + continuationWebSocketFrame.content() + "是否为最终分片：" + finalFragment);
        if (null == buf) {
            buf = ctx.alloc().buffer();
        }
        buf.writeBytes(continuationWebSocketFrame.content());

        if (finalFragment) {
            System.out.println("数据整合结果：" + buf);
            ChannelFuture future = ctx.writeAndFlush(new BinaryWebSocketFrame(buf));
            future.addListener(new GenericFutureListener<Future<? super Void>>() {
                @Override
                public void operationComplete(Future<? super Void> future) throws Exception {
                    boolean success = future.isSuccess();
                    System.out.println(success);
                    if (success) {
                        buf = null;
                    }
                }
            });
        }
    }
}
